package com.minhua.jijiehao2.mainframe.home.homeFragment.impl

import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import com.bigkoo.convenientbanner.ConvenientBanner
import com.bumptech.glide.Glide
import com.minhua.jijiehao2.R
import com.minhua.jijiehao2.base.BaseFragment
import com.minhua.jijiehao2.base.adapter.ViewHolder
import com.minhua.jijiehao2.base.adapter.recyclerview.BaseCommonAdapter
import com.minhua.jijiehao2.bean.ChannelBean
import com.minhua.jijiehao2.bean.HomeBannerBean
import com.minhua.jijiehao2.bean.HomeMenuBean
import com.minhua.jijiehao2.mainframe.common.imageactivity.impl.ImageActivity
import com.minhua.jijiehao2.mainframe.common.shareactivity.impl.ShareActivity
import com.minhua.jijiehao2.mainframe.common.webviewactivity.impl.WebActivity
import com.minhua.jijiehao2.mainframe.home.homeFragment.imp.IHomeView
import com.minhua.jijiehao2.mainframe.home.menulistactivity.impl.MenuListActivity
import com.minhua.jijiehao2.mainframe.launcher.loginactivity.impl.LoginActivity
import com.minhua.jijiehao2.mainframe.main.impl.MainActivity
import com.minhua.jijiehao2.utils.CountUtils
import com.minhua.jijiehao2.utils.HomeImgBannerHolder
import kotlinx.android.synthetic.main.fragment_home.*

class HomeFragment : BaseFragment<IHomeView, HomePresenter>(), IHomeView {
    override fun getLayoutId(): Int = R.layout.fragment_home

    override fun getPresenter(): HomePresenter = HomePresenter()

    companion object {

        fun newInstance(): HomeFragment {
            val fragment = HomeFragment()
            val args = Bundle()
            fragment.arguments = args
            return fragment
        }
    }


    private val banners = ArrayList<HomeBannerBean.PicsBean>()

    private val channels = ArrayList<ChannelBean>()
    private var channelsAdapter: BaseCommonAdapter<ChannelBean>? = null

    private val menus = ArrayList<HomeMenuBean>()
    private var menusAdapter: BaseCommonAdapter<HomeMenuBean>? = null

    override fun initView() {
        banner
                //设置指示器是否可见
                .setPointViewVisible(true)
                //设置自动切换（同时设置了切换时间间隔）
                .startTurning(2000)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(intArrayOf(R.mipmap.guide_point, R.mipmap.guide_point_cur))
                //设置指示器的方向（左、中、右）
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL).isManualPageable = true
        banner.setPages({ HomeImgBannerHolder() }, banners)

        banner.setOnItemClickListener { position ->
            val bannerBean = banners[position]
            val wUrl = bannerBean.getwUrl()
            val pCode = bannerBean.pcode

            if (TextUtils.isEmpty(wUrl)) {
                if (!TextUtils.isEmpty(pCode)) {
//                    ChannelDetailActivity.intentStart(activity, pCode, bannerBean.id)
                    if(LoginActivity.logged(activity)){
                        WebActivity.intentStart(activity, bannerBean.url, "详情")
                    }
                }
            } else {
                if (TextUtils.isEmpty(pCode)) {
                    ImageActivity.intentStart(activity, wUrl)
                } else {
                    if (wUrl.contains("type=share")) {
                        if (LoginActivity.logged(activity)) {
                            startActivity(Intent(activity, ShareActivity::class.java))
                        }
                    } else {
                        WebActivity.intentStart(activity, wUrl, "详情")
                    }
                }
            }
        }

        channelsAdapter = object : BaseCommonAdapter<ChannelBean>(activity, R.layout.item_channel_list, channels) {
            override fun convert(holder: ViewHolder?, t: ChannelBean?) {
                holder?.setText(R.id.tvName, t?.pname ?: "")
                holder?.setText(R.id.tvMessage, t?.pmessage ?: "")
                val split = t?.ptag?.split("|")
                if (split != null) {
                    if (split.size == 1) {
                        holder?.setText(R.id.tvTagLeft, split[0])
                        holder?.setVisible(R.id.tvTagCenter, View.INVISIBLE)
                    } else {
                        holder?.setText(R.id.tvTagLeft, split[0])
                        holder?.setVisible(R.id.tvTagCenter, View.VISIBLE)
                        holder?.setText(R.id.tvTagCenter, split[1])
                    }
                }
                holder?.setText(R.id.tvDate, "日利率:" + t?.pinterest + "%")
                holder?.setText(R.id.tvNum, "申请人数:" + t?.pBorrowNum)
                if (TextUtils.isEmpty(t?.pmarks)) {
                    holder?.setVisible(R.id.rlTab, View.GONE)
                } else {
                    holder?.setText(R.id.tvTag, t?.pmarks ?: "")
                }

                Glide.with(activity).load(t?.picUrl).into(holder?.getView(R.id.ivChannelIcon))
                Glide.with(activity).load(t?.backgroundImage).into(holder?.getView(R.id.ivTag))
                holder?.setOnClickListener(R.id.rlItemView, {
                    //                    ChannelDetailActivity.intentStart(activity, t)
                    if(LoginActivity.logged(activity)){
                        WebActivity.intentStart(activity, t?.phttp!!, t.pname)
                    }
                })
            }
        }
        rvContent.isNestedScrollingEnabled = false
        rvContent.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        rvContent.adapter = channelsAdapter

        menusAdapter = object : BaseCommonAdapter<HomeMenuBean>(activity, R.layout.item_home_menu, menus) {
            override fun convert(holder: ViewHolder?, t: HomeMenuBean?) {
                Glide.with(activity).load(t?.picUrl).into(holder?.getView(R.id.ivItemIcon))
                holder?.setText(R.id.tvItemName, t?.title ?: "")
                holder?.setOnClickListener(R.id.llItemView, {
                    if (t != null) {
                        //轨迹记录
                        CountUtils.recodeDetail(CountUtils.SORTPIC, t.id.toString())
                        if (t.id == 64) {
                            //信用卡
                            MainActivity.intentStart(activity, 3)
                        } else {
                            MenuListActivity.intentStart(activity, t.id, t.title)
                        }
                    }
                })
            }
        }
        rvMenu.isNestedScrollingEnabled = false
        rvMenu.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
        rvMenu.adapter = menusAdapter

        refresh.setOnRefreshListener { initData() }
        llNotice.setOnClickListener{

        }
    }

    override fun initData() {
        mPresenter.getBannerInfo()
        mPresenter.getHotInfo()
        mPresenter.getMenuInfo()
    }

    override fun onBannerSuccess(homeBannerBean: HomeBannerBean) {
        val pics = homeBannerBean.pics
        if (pics != null && pics.size > 0) {
            banners.clear()
            banners.addAll(pics)
            banner.notifyDataSetChanged()
        }

        val radios = homeBannerBean.radios
        val textList = ArrayList<String>()
        radios
                .map { it.radio }
                .filterNotTo(textList) { TextUtils.isEmpty(it) }

        if (radios != null && radios.size > 0) {
            tvNotice.setData(textList)
        }
    }

    override fun onHotChannelSuccess(list: List<ChannelBean>) {
        refresh.isRefreshing = false
        if (list.isNotEmpty()) {
            channels.clear()
            channels.addAll(list)
            channelsAdapter?.notifyDataSetChanged()
        }
    }

    override fun onMenuSuccess(list: List<HomeMenuBean>) {
        if (list.isNotEmpty()) {
            menus.clear()
            menus.addAll(list)
            menusAdapter?.notifyDataSetChanged()
        }
    }
}
